/*
  封装常用的http函数,api通过定义XXApi定义,page里引入XXApi来操作
*/
const env = require('env.js')
const storage = require('../utils/storage');

function get(url,param,need_auth){

  return ajax(url,param,"GET",need_auth);

}
function post(url,param,need_auth){
  return ajax(url,param,"POST",need_auth);
}
function deletex(url,param,need_auth) {
  return ajax(url,param,"DELETE",need_auth);
}
function ajax(url,data,method,need_auth) {
  let header = {}
  if(need_auth) {
    header["Authorization"] = storage.getItem("token");
  }
  return new Promise((resolve,reject)=>{
    wx.showLoading({
      title: '请求网络中',
    })
    console.log("request:"+(env.apiUrl+url));
    wx.request({
      url: env.apiUrl+url,
      method:method,
      data:data,
      header:header,
      success:function(res){
              if(res.statusCode==200) {
                  resolve(res.data);
              }
              if(res.statusCode==500) {
                wx.showToast({
                  title: res.data.message,
                  icon:'none'
                })
              }else if(res.statusCode==401) {
                wx.showToast({
                  title: "身份失效，请重新登录",
                  icon:'none'
                });
                storage.setItem("token",null);
                wx.showModal({
                  title:"提示",
                  content:"请先登录",
                  success:(res)=>{
                    if(res.confirm) {
                      wx.redirectTo({
                        url: '/pages/profile/profile',
                      })
                    } else {
                      wx.navigateBack()
                    }
                    
                  }
                })
              }
            
      },
      fail:(err)=>{
        wx.showToast({
          title: '请求网络失败',
          icon:"error",
          duration:2500
        })
        wx.showModal({
          content:"请求:"+(env.apiUrl+ url)+"失败!"
        })
        reject(err);
      },
      complete:()=>{
          wx.hideLoading({
            success: (res) => {},
          })
      }
    });
  });
  
}

module.exports.post = post;
module.exports.get = get;
module.exports.deletex=deletex;